package com.yuebook.smartrpc.framework.serialization.engine;

import com.google.common.collect.Maps;
import com.yuebook.smartrpc.framework.serialization.common.SerializerType;
import com.yuebook.smartrpc.framework.serialization.serializer.ISerializer;
import com.yuebook.smartrpc.framework.serialization.serializer.impl.DefaultJavaSerializer;
import com.yuebook.smartrpc.framework.serialization.serializer.impl.FastJsonSerializer;
import com.yuebook.smartrpc.framework.serialization.serializer.impl.HessianSerializer;
import com.yuebook.smartrpc.framework.serialization.serializer.impl.ProtoStuffSerializer;
import java.util.Map;

/**
 * @author honglei
 * @date 2018/11/19 下午9:23
 */
public class SerializerEngine {

    public static final Map<SerializerType, ISerializer> serializerMap = Maps.newConcurrentMap();

    static {
        serializerMap.put(SerializerType.SERIALIZER_DEFAULTJAVA, new DefaultJavaSerializer());
        serializerMap.put(SerializerType.SERIALIZER_HESSIAN, new HessianSerializer());
        serializerMap.put(SerializerType.SERIALIZER_FASTJSON, new FastJsonSerializer());
        serializerMap.put(SerializerType.SERIALIZER_PROTOSTUFF, new ProtoStuffSerializer());
    }


    public static <T> byte[] serialize(T obj, String serializeType) {
        SerializerType serialize = SerializerType.queryType(serializeType);
        if (serialize == null) {
            throw new RuntimeException("serialize is null");
        }

        ISerializer serializer = serializerMap.get(serialize);
        if (serializer == null) {
            throw new RuntimeException("serialize error");
        }

        try {
            return serializer.serialize(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> T deserialize(byte[] data, Class<T> clazz, String serializeType) {

        SerializerType serialize = SerializerType.queryType(serializeType);
        if (serialize == null) {
            throw new RuntimeException("serialize is null");
        }
        ISerializer serializer = serializerMap.get(serialize);
        if (serializer == null) {
            throw new RuntimeException("serialize error");
        }

        try {
            return serializer.deserialize(data, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
